package com.vma.shoeSystem.controller;

import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Page;
import com.vma.shoeSystem.util.ReturnsUtil;
import com.vma.shoes.bizModel.model.Brand;
import com.vma.shoes.bizModel.model.Offer;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by chenzui on 2017/4/2.
 */
public class BrandController extends Controller{
    public void add(){
        try {
            String brandName = getPara("brandName");
            new Brand().setCreateTime(new Date()).setIfDelete("0").setBrandName(brandName).save();
            renderJson(ReturnsUtil.returnSuccess("新增品牌成功"));
        }catch (Exception e){
            e.printStackTrace();
            renderJson(ReturnsUtil.returnException(e.getMessage(),e));
        }

    }

    public void update(){
        try {
            String brandName = getPara("brandName");
            Brand.dao.findById(getPara("id")).setBrandName(brandName).update();
            renderJson(ReturnsUtil.returnSuccess("修改品牌成功"));
        }catch (Exception e){
            e.printStackTrace();
            renderJson(ReturnsUtil.returnException(e.getMessage(),e));
        }

    }
    public void delete(){
        try {
            List offers = Offer.dao.find("select * from offer where brand_id = ?",getPara("id"));
            if(offers == null || offers.size() == 0){
                Brand.dao.findById(getPara("id")).setIfDelete("1").update();
                renderJson(ReturnsUtil.returnSuccess("删除"));
            }else {
                renderJson(ReturnsUtil.returnFail("该品牌存在商品","-1"));

            }

        }catch (Exception e){
            e.printStackTrace();
            renderJson(ReturnsUtil.returnException(e.getMessage(),e));
        }

    }

    public void qryBrandList(){
        try {
            String brandName = getPara("brandName");

            int pageNo = getParaToInt("cPage");
            int pageSize = getParaToInt("pSize");

            List<String> param = new ArrayList<String>();
            String condition = "";


            if(brandName != null && !"".equals(brandName)){
                condition += "and brand_name like ? ";
                param.add("%"+brandName+"%");
            }
            Page<Brand> brandPage = Brand.dao.paginate(pageNo,pageSize,"select * ","from brand where if_delete = 0 "+condition+
                            " order by create_time desc"
                    ,param.toArray());
            renderJson(ReturnsUtil.returnSuccess(brandPage));
        }catch (Exception e){
            e.printStackTrace();
            renderJson(ReturnsUtil.returnException(e.getMessage(),e));
        }
    }
}
